import { PathVariables } from "./types";

function isValidPathVariable(value: any): value is string | number {
  return typeof value === "string" || typeof value === "number";
}

// 拼接 URL 参数
export const buildUrlWithPathVariables = <
  U extends string,
  P = PathVariables<U>
>(
  url: U,
  pathVariables?: P,
  defaultValues?: Record<string, string | number>
): string => {
  if (!pathVariables && !defaultValues) return url;

  // 使用类型断言来确保累加器类型为 string
  return Object.entries(pathVariables || {}).reduce((acc, [key, value]) => {
    // 验证路径变量值的有效性
    if (isValidPathVariable(value)) {
      // 类型断言告诉 TypeScript acc 仍然是 string
      return acc.replace(`{${key}}`, String(value));
    } else if (defaultValues && isValidPathVariable(defaultValues[key])) {
      // 使用默认值替换路径变量
      return acc.replace(`{${key}}`, String(defaultValues[key]));
    } else {
      throw new Error(`Invalid value for path variable: ${key}`);
    }
  }, url as string); // 强制将初始值断言为 string 类型
};
